package com.beaven.model.data.user;

import android.text.TextUtils;
import com.beaven.model.data.helper.DbHelper;
import com.beaven.model.data.helper.UserHelper;
import com.beaven.model.model.card.CategoryCard;
import com.beaven.model.model.card.UserCard;
import com.beaven.model.model.db.Category;
import com.beaven.model.model.db.User;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;
import timber.log.Timber;

/**
 * author: Beaven
 * time: 2017/5/27 16:15
 */

public class UserDispatcher implements UserCenter {

  private static volatile UserDispatcher instance;
  private List<User> userList;
  private List<Category> categoryList;

  public static UserDispatcher getInstance() {
    if (instance == null) {
      synchronized (UserDispatcher.class) {
        if (instance == null) {
          instance = new UserDispatcher();
        }
      }
    }
    return instance;
  }

  private UserDispatcher() {
  }

  @Override public void dispatchUser(final UserCard... cards) {
    userList = new ArrayList<>();
    Observable.from(cards).subscribeOn(Schedulers.io()).subscribe(new Subscriber<UserCard>() {
      @Override public void onCompleted() {
        DbHelper.instance().saveModel(User.class, userList.toArray(new User[0]));
      }

      @Override public void onError(Throwable e) {
        Timber.e("好友分发-Error--" + e);
      }

      @Override public void onNext(UserCard userCard) {
        if (!TextUtils.isEmpty(userCard.getId())) {
          userList.add(userCard.build());
        }
      }
    });
  }

  @Override public void dispatchCategory(final List<CategoryCard> cards) {
    categoryList = new ArrayList<>();
    Observable.from(cards).subscribeOn(Schedulers.io()).subscribe(new Subscriber<CategoryCard>() {
      @Override public void onCompleted() {
        DbHelper.instance().saveModel(Category.class, categoryList.toArray(new Category[0]));
      }

      @Override public void onError(Throwable e) {
        Timber.e("分组分发-Error--" + e);
      }

      @Override public void onNext(CategoryCard categoryCard) {
        if (!TextUtils.isEmpty(categoryCard.getId())) {
          Category category = UserHelper.findCategory(categoryCard.getId());
          if (category == null) {
            categoryList.add(categoryCard.build(new Category()));
          } else {
            categoryList.add(categoryCard.build(category));
          }
        }
      }
    });
  }
}
